﻿using Newtonsoft.Json.Linq;
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Linq;

namespace DBWorks.Sharepoint2013.Twitter
{
    [ToolboxItemAttribute(false)]
    public partial class Twitter : WebPart
    {
        [WebBrowsable(true),
        WebDisplayName("oAuth Token"),
        WebDescription(""),
        Personalizable(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
        Category("Configurações")]
        public string oAuth_token { get; set; }

        [WebBrowsable(true),
         WebDisplayName("oAuth Token Secret"),
         WebDescription(""),
         Personalizable(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
         Category("Configurações")]
        public string oAuth_token_secret { get; set; }

        [WebBrowsable(true),
         WebDisplayName("oAuth Consumer Key"),
         WebDescription(""),
         Personalizable(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
         Category("Configurações")]
        public string oAuth_consumer_key { get; set; }

        [WebBrowsable(true),
         WebDisplayName("oAuth Consumer Secret"),
         WebDescription(""),
         Personalizable(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
         Category("Configurações")]
        public string oAuth_consumer_secret { get; set; }

        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public Twitter()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        public string query = "umerpasha";
        //    public string url = "https://api.twitter.com/1.1/users/search.json" ;
        public string url = "https://api.twitter.com/1.1/statuses/user_timeline.json";


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(oAuth_token)
                && !string.IsNullOrWhiteSpace(oAuth_token_secret)
                && !string.IsNullOrWhiteSpace(oAuth_consumer_key)
                && !string.IsNullOrWhiteSpace(oAuth_consumer_secret))
                findUserTwitter(url, query);
        }

        public void findUserTwitter(string resource_url, string q)
        {

            // oauth application keys
            var oauth_token = oAuth_token; 
            var oauth_token_secret = oAuth_token_secret; 
            var oauth_consumer_key = oAuth_consumer_key; 
            var oauth_consumer_secret = oAuth_consumer_secret; 

            // oauth implementation details
            var oauth_version = "1.0";
            var oauth_signature_method = "HMAC-SHA1";

            // unique request details
            var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            var timeSpan = DateTime.UtcNow
                - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();


            // create oauth signature
            var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                            "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";

            var baseString = string.Format(baseFormat,
                                        oauth_consumer_key,
                                        oauth_nonce,
                                        oauth_signature_method,
                                        oauth_timestamp,
                                        oauth_token,
                                        oauth_version,
                                        Uri.EscapeDataString(q)
                                        );

            baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

            var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                    "&", Uri.EscapeDataString(oauth_token_secret));

            string oauth_signature;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(
                    hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }

            // create the request header
            var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                               "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                               "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                               "oauth_version=\"{6}\"";

            var authHeader = string.Format(headerFormat,
                                    Uri.EscapeDataString(oauth_nonce),
                                    Uri.EscapeDataString(oauth_signature_method),
                                    Uri.EscapeDataString(oauth_timestamp),
                                    Uri.EscapeDataString(oauth_consumer_key),
                                    Uri.EscapeDataString(oauth_token),
                                    Uri.EscapeDataString(oauth_signature),
                                    Uri.EscapeDataString(oauth_version)
                            );



            ServicePointManager.Expect100Continue = false;

            // make the request
            var postBody = "q=" + Uri.EscapeDataString(q);//
            resource_url += "?" + postBody;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
            request.Headers.Add("Authorization", authHeader);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            var response = (HttpWebResponse)request.GetResponse();
            var reader = new StreamReader(response.GetResponseStream());
            var objText = reader.ReadToEnd();
            //myDiv.InnerHtml += objText;/**/
            string html = "";
            var twitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
            try
            {
                JArray jsonDat = JArray.Parse(objText);
                for (int x = 0; x < jsonDat.Count(); x++)
                {
                    var data = DateTime.ParseExact(jsonDat[x]["created_at"].ToString(), twitterDateTemplate, new System.Globalization.CultureInfo("en-US"));
                    html += "<div  class='twitterpostsitem'><div class='twitterpostsitemtime'>" + getTimeFromDate(data) + "</div>";
                    //html += jsonDat[x]["id"].ToString() + "<br/>";
                    html += "<div class='twitterpostsitemtext'>" + jsonDat[x]["text"].ToString() + "</div></div>";
                    // html += jsonDat[x]["name"].ToString() + "<br/>";
                }
                TwitterDiv.InnerHtml += html;
            }
            catch (Exception twit_error)
            {
                TwitterDiv.InnerHtml += html + twit_error.ToString();
            }
        }

        private string getTimeFromDate(DateTime pubDate)
        {
            TimeSpan diff = DateTime.Now - pubDate;
            string tempo = string.Empty;
            if (diff.Days >= 365)
                tempo = (diff.Days / 365).ToString() + "a";
            else if (diff.Days > 0)
                tempo = diff.Days.ToString() + "d";
            else if (diff.Hours > 0)
                tempo = diff.Hours.ToString() + "h";
            else if (diff.Minutes > 0)
                tempo = diff.Hours.ToString() + "m";
            else
                tempo = "now";

            return tempo;
        }
    }
}
